package com.mercenary.wein.screenControl.ui;

import com.android.ddmlib.NullOutputReceiver;
import com.mercenary.wein.screenControl.bean.DeviceBean;
import com.mercenary.wein.screenControl.command.CommandTool;
import com.mercenary.wein.screenControl.command.jobSchedual.InitJob;
import com.mercenary.wein.screenControl.deviceControll.AndroidDevice;
import com.mercenary.wein.screenControl.deviceControll.DeviceControlDecorator;
import com.mercenary.wein.screenControl.deviceControll.DevicesDetector;
import com.mercenary.wein.screenControl.service.DeviceService;
import com.mercenary.wein.screenControl.ui.batch.*;
import com.mercenary.wein.screenControl.ui.listener.*;
import com.mercenary.wein.screenControl.ui.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

//J3面板是显示手机屏幕的面板
public class MainFrame extends JFrame {
    FlowLayout layout1 = new FlowLayout(1, 120, 20);    
	FlowLayout layout2 = new FlowLayout(1, 120, 20);
    GridLayout layout3 = new GridLayout(0, 2);//Layout(1,120,20);
    FlowLayout layout4 = new FlowLayout();

    JTextArea area = new JTextArea();
    JPanel phoneShow = new JPanel();
    JPanel J2 = new JPanel(new BorderLayout());
    JScrollPane J3 = new JScrollPane(phoneShow);
    JPanel J4 = new JPanel();
    JPanel J5 = new JPanel();
    JPanel J6 = new JPanel();
    JPanel J7 = new JPanel();
    JPanel Joperation = new JPanel();//存放列表
    JPanel Joperation1 = new JPanel();
    JPanel Joperation2 = new JPanel();
    JPanel Joperation3 = new JPanel();
    JTabbedPane tabPanel = new JTabbedPane();
    //显示设备面板按钮
    JButton B6 = new JButton("显示");
    JButton B7 = new JButton("断开");
    JButton newBUTTON = new JButton("新建分组");
    //单，群控面板按钮
    JRadioButton JRB1 = new JRadioButton("单控");
    JRadioButton JRB2 = new JRadioButton("群控");
    //JTextField T1=new JTextField("全部设备");
    //批量操作的按钮
    JButton batchB10 = new JButton("安装apk");
    JButton batchB1 = new JButton("打开微信");
    JButton batchB2 = new JButton("打开qq");
    JButton batchB3 = new JButton("打开浏览器");
    JButton batchB4 = new JButton("返回主界面");
    JButton batchB5 = new JButton("打开手机屏幕");
    JButton batchB6 = new JButton("关闭手机屏幕");
    JButton batchB7 = new JButton("打开飞行模式");
    JButton batchB8 = new JButton("关闭飞行模式");
    JButton batchB9 = new JButton("打开手机");
    JButton batchB0 = new JButton("关闭手机");
    //微信操作的按钮
    JButton wxB1 = new JButton("导入通讯录");
    JButton wxB2 = new JButton("添加通讯录好友");
    JButton wxB3 = new JButton("添加群聊好友");
    JButton wxB4 = new JButton("添加搜索好友");
    JButton wxB5 = new JButton("发朋友圈");
    JButton wxB6 = new JButton("群发消息");
    JButton wxB7 = new JButton("打招呼");
    JButton wxB8 = new JButton("接受打招呼");
    JButton wxB9 = new JButton("接受好友请求");
    JButton wxB0 = new JButton("模拟定位");
    JButton wxBa = new JButton("接受摇一摇打招呼");
    JButton wxBb = new JButton("朋友圈点赞");
    JButton wxBc = new JButton("当前任务");
    JButton wxBd = new JButton("清理僵尸粉");
    JButton wxBe = new JButton("摇一摇");
    //设备信息的按钮
    JPanel Jtitle = new JPanel();
    JLabel JLabel1 = new JLabel("在线设备");
    JTextField num = new JTextField();
    JLabel JLabel2 = new JLabel("台");
    DeviceTable deviceTable = new DeviceTable();

    //全局变量
    //保存页面所有显示设备的Map
    public static final Map<String, DeviceControlDecorator> dcdMap = new HashMap<String, DeviceControlDecorator>();
    //保存所有连接上的设备的Map
    public static final Map<String, DeviceBean> dbMap = new HashMap<String, DeviceBean>();
    //保存被选择的设备id
    public static final List<String> choosedDevice = new ArrayList<String>();


    public MainFrame() {
        super("微群控");

    }

    public static void main(String[] args) {
        Log log = LogFactory.getLog(MainFrame.class);


        new MainFrame().init();
    }


    public void constructBatch() {
        batchB1.setPreferredSize(new Dimension(100, 30));
        batchB2.setPreferredSize(new Dimension(100, 30));
        batchB3.setPreferredSize(new Dimension(100, 30));
        batchB4.setPreferredSize(new Dimension(100, 30));
        batchB5.setPreferredSize(new Dimension(100, 30));
        batchB6.setPreferredSize(new Dimension(100, 30));
        batchB7.setPreferredSize(new Dimension(100, 30));
        batchB8.setPreferredSize(new Dimension(100, 30));
        batchB9.setPreferredSize(new Dimension(100, 30));
        batchB0.setPreferredSize(new Dimension(100, 30));
        FlowLayout layout = new FlowLayout(1, 120, 20);// layout=new BoxLayout(Joperation, BoxLayout.PAGE_AXIS);
        Joperation2.setLayout(layout);
        Joperation2.add(batchB10);
        batchB10.addActionListener(new UploadListener("install", Joperation2, deviceTable));
        Joperation2.add(batchB1);
        Joperation2.add(batchB2);
        Joperation2.add(batchB3);
        Joperation2.add(batchB4);
        Joperation2.add(batchB5);
        Joperation2.add(batchB6);
        Joperation2.add(batchB7);
        Joperation2.add(batchB8);
        Joperation2.add(batchB9);
        Joperation2.add(batchB0);
    }

    public void constructWX() {
        FlowLayout layout = new FlowLayout(1, 120, 5);// layout=new BoxLayout(Joperation, BoxLayout.PAGE_AXIS);
        Joperation1.setLayout(layout);
        wxB1.setPreferredSize(new Dimension(160, 30));
        wxB2.setPreferredSize(new Dimension(160, 30));
        wxB3.setPreferredSize(new Dimension(160, 30));
        wxB4.setPreferredSize(new Dimension(160, 30));
        wxB5.setPreferredSize(new Dimension(160, 30));
        wxB6.setPreferredSize(new Dimension(160, 30));
        wxB7.setPreferredSize(new Dimension(160, 30));
        wxB8.setPreferredSize(new Dimension(160, 30));
        wxB9.setPreferredSize(new Dimension(160, 30));
        wxB0.setPreferredSize(new Dimension(160, 30));
        wxBa.setPreferredSize(new Dimension(160, 30));
        wxBb.setPreferredSize(new Dimension(160, 30));
        wxBc.setPreferredSize(new Dimension(160, 30));
		wxBd.setPreferredSize(new Dimension(160, 30));
        wxBe.setPreferredSize(new Dimension(160, 30));
        Joperation1.add(wxB1);
        Joperation1.add(wxB2);
        Joperation1.add(wxB3);
        Joperation1.add(wxB4);
        Joperation1.add(wxB5);
        Joperation1.add(wxB6);
        Joperation1.add(wxB7);
        Joperation1.add(wxB8);
        Joperation1.add(wxB9);
        Joperation1.add(wxB0);
        Joperation1.add(wxBa);
        Joperation1.add(wxBb);
        Joperation1.add(wxBc);
		Joperation1.add(wxBd);
        Joperation1.add(wxBe);
    }

    public void constructDeviceList() {
        Joperation.setLayout(new BorderLayout());
        Jtitle.setLayout(layout4);
        Jtitle.add(JLabel1);
        Jtitle.add(num);
        Jtitle.add(JLabel2);
        //设置在线手机总数
        num.setText("0");
        num.setEditable(false);
        num.setPreferredSize(new Dimension(30, 30));
        Jtitle.setPreferredSize(new Dimension(100, 30));
        Jtitle.setBackground(Color.LIGHT_GRAY);
        Joperation.add(Jtitle, BorderLayout.NORTH);
        Joperation.add(deviceTable, BorderLayout.CENTER);
        Joperation.validate();
    }
    public void constructMessageList(){
        Joperation3.setLayout(new BorderLayout());
        JButton jb1=new JButton("打开集中聊天");
        jb1.setPreferredSize(new Dimension(100, 30) );
        Joperation3.add(jb1,BorderLayout.NORTH);
        jb1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MessageList LIST=new  MessageList ();
                J3.validate();
                //tabPanel.setVisible(true);
            }
        });
        Joperation3.validate();
    }
    public void constructTabPanel() {
        tabPanel.add("设备", Joperation);
        tabPanel.add("批量", Joperation1);
        tabPanel.add("微控", Joperation2);
        tabPanel.add("信息", Joperation3);
        J2.add(tabPanel, BorderLayout.WEST);
        J2.add(J4, BorderLayout.SOUTH);
    }

    public void init() {

        J3.setPreferredSize(new Dimension(1050, 600));//设置大小
        J4.setPreferredSize(new Dimension(200, 180));
        J5.setPreferredSize(new Dimension(200, 80));
        J7.setPreferredSize(new Dimension(200, 100));
        tabPanel.setPreferredSize(new Dimension(300, 800));
        Joperation.setPreferredSize(new Dimension(120, 800));
        Joperation1.setPreferredSize(new Dimension(120, 800));
        Joperation2.setPreferredSize(new Dimension(120, 800));
        Joperation3.setPreferredSize(new Dimension(120, 800));
		J4.setLayout(new BorderLayout());

        //调整手机屏幕的缩放@涂笑
        final JSlider s = new JSlider(0, 100, 0);
        s.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                // TODO Auto-generated method stub
                if (e.getSource() == s) {

                }
            }

        });

        final GroupComboBox comboBox = new GroupComboBox();
        comboBox.registerObserver(deviceTable);
		FlowLayout layout = new FlowLayout();
        layout.setVgap(30);
        B6.setPreferredSize(new Dimension(100, 30));
        B7.setPreferredSize(new Dimension(100, 30));
        newBUTTON.setPreferredSize(new Dimension(100, 30));
        comboBox.setPreferredSize(new Dimension(100, 30));
        J5.add(B6);
        J5.add(B7);
        J7.add(newBUTTON);
        J7.add(comboBox);
        J4.add(s,BorderLayout.NORTH);
    	J4.add(J5,BorderLayout.CENTER);
    	J4.add(J7,BorderLayout.SOUTH);
        comboBox.setPreferredSize(new Dimension(100, 30));
        J5.validate();
        J6.validate();
        batchB1.setPreferredSize(new Dimension(100, 30));
        batchB2.setPreferredSize(new Dimension(100, 30));
        batchB3.setPreferredSize(new Dimension(100, 30));
        batchB4.setPreferredSize(new Dimension(100, 30));
        batchB5.setPreferredSize(new Dimension(100, 30));
        batchB6.setPreferredSize(new Dimension(100, 30));
        batchB7.setPreferredSize(new Dimension(100, 30));
        batchB8.setPreferredSize(new Dimension(100, 30));
        batchB9.setPreferredSize(new Dimension(100, 30));
        batchB0.setPreferredSize(new Dimension(100, 30));
        wxB1.setPreferredSize(new Dimension(100, 30));
        wxB2.setPreferredSize(new Dimension(100, 30));
        wxB3.setPreferredSize(new Dimension(100, 30));
        wxB4.setPreferredSize(new Dimension(100, 30));
        wxB5.setPreferredSize(new Dimension(100, 30));
        wxB6.setPreferredSize(new Dimension(100, 30));
        wxB7.setPreferredSize(new Dimension(100, 30));
        wxB8.setPreferredSize(new Dimension(100, 30));
        wxB9.setPreferredSize(new Dimension(100, 30));


        constructWX();
        constructBatch();
        constructDeviceList();
		constructMessageList();
        constructTabPanel();

        setLayout(new BorderLayout());
        setVisible(true);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(J2, BorderLayout.CENTER);
        add(J3, BorderLayout.EAST);

        //显示按钮的点击事件,即手机屏幕投屏??
        B6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                J3.validate();
                //tabPanel.setVisible(true);
            }
        });
        ////断开按钮的点击事件，即手机屏幕与pc断开?
        B7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                J3.validate();
                //tabPanel.setVisible(true);
            }
        });
        //新建分组的按钮点击事件????
        newBUTTON.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //新建分组的弹出框
                //String inputValue = JOptionPane.showInputDialog("请输入分组名称");
                InputDialog inputdialog = new InputDialog(MainFrame.this);
                inputdialog.registerGroupComboBox(comboBox);
                Joperation.validate();
                //tabPanel.setVisible(true);
            }
        });


        //打开微信按钮点击事件，点击该按钮后，群控模式下在线手机打开微信主界面
        batchB1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.openWeChat(getChoosedDeviceBeanList());
            }
        });
        //打开qq按钮点击事件，点击该按钮后，群控模式下在线手机打开qq界面
        batchB2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.openQQ(getChoosedDeviceBeanList());
            }
        });
        //打开浏览器按钮点击事件，点击该按钮后，群控模式下在线手机打开浏览器界面
        batchB3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.openIE(getChoosedDeviceBeanList());
            }
        });
        //返回主界面按钮点击事件，点击该按钮后，群控模式下在线手机回到主界面
        batchB4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.openMainPage(getChoosedDeviceBeanList());
            }
        });
        //打开手机屏幕按钮点击事件，点击该按钮后，群控模式下在线手机打手机屏幕（解锁）
        batchB5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.openScreen(getChoosedDeviceBeanList());
            }
        });
        //关闭手机屏幕按钮点击事件，点击该按钮后，群控模式下在线手机关闭手机屏幕
        batchB6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.closeScreen(getChoosedDeviceBeanList());
            }
        });
        //打开飞行模式点击事件，点击该按钮后，群控模式下在线手机将打开飞行模式
        batchB7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.openFlyMode(getChoosedDeviceBeanList());
            }
        });
        //关闭飞行模式点击事件，点击该按钮后，群控模式下在线手机将关闭飞行模式
        batchB8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.closeFlyMode(getChoosedDeviceBeanList());
            }
        });
        //打开手机按钮点击事件，点击该按钮后，群控模式下在线手机重启
        batchB9.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.reboot(getChoosedADeviceBeanList());
            }
        });
        //关闭手机按钮点击事件，点击该按钮后，群控模式下在线手机关机
        batchB0.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CommandTool.shutdown(getChoosedADeviceBeanList());
            }
        });
        //导入通讯录按钮的处理事件
        wxB1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ImportAddressBook A = new ImportAddressBook();


            }
        });
        //模拟定位按钮的处理事件
        //模拟定位按钮的处理事件
        wxB0.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                LocationOperation B = new LocationOperation();


            }
        });
        wxB2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddAddressBookFriend B = new AddAddressBookFriend();


            }
        });
        wxB3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddGroupChatFriend B = new AddGroupChatFriend();


            }
        });
        wxB4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddSearchFriend B = new AddSearchFriend();


            }
        });

        //模拟定位按钮的处理事件
        wxB5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SendStateInFriendCircle C = new SendStateInFriendCircle();


            }
        });
        wxB6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MassMessage C = new MassMessage();


            }
        });

        //一打招呼按钮的处理事件？？？
        wxB7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Greet D = new Greet();
                ;


            }
        });
        wxB8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AcceptNearbyGreet D = new AcceptNearbyGreet();
                ;


            }
        });
        //一键接受好友请求按钮的处理事件？？？
        wxB9.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AcceptFriendRequest E = new AcceptFriendRequest();


            }
        });
        wxBa.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AcceptShakeGreet F = new AcceptShakeGreet();


            }
        });
        wxBb.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                FriendPunctuatePraise B = new FriendPunctuatePraise();


            }
        });
        wxBc.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CurrentTask B = new CurrentTask();


            }
        });

        wxBd.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                CleanTheZombie B=new CleanTheZombie();


            }
        } );
        wxBe.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                Shake B=new Shake();


            }
        } );

        //-------初始化设备界面

        final DevicesDetector devicesDetector = DevicesDetector.getInstance();

        final DeviceService deviceService = new DeviceService();
        deviceService.resetDeviceStatus();
        int i = 0;
        for (AndroidDevice androidDevice : devicesDetector.getDevicesMap().values()) {
            //TODO 一个bug，连接时间长后悔出现若干个模拟器，怀疑是monkey的干扰
            if (androidDevice.getSerialNo().startsWith("emulator")) continue;

            DeviceBean deviceBean = deviceService.registerDevice(androidDevice);
            dbMap.put(deviceBean.getSerialNo(), deviceBean);
            androidDevice.createForward(deviceBean.getPort(), 3321);
            androidDevice.executeShellCommand("am start -n com.zoke.wechatautomate/com.zoke.wechatautomate.MainActivity", new NullOutputReceiver());
//
//            MyPanel myPanel = new MyPanel(androidDevice.getDevice(),deviceBean.getPort());
//            myPanel.setPreferredSize(new Dimension(270,480));
//            a.add(myPanel);

//            DeviceControlDecoratorPlus dcd = new DeviceControlDecoratorPlus(androidDevice,deviceBean.getPort());
            DeviceControlDecorator dcd = new DeviceControlDecorator(androidDevice);
            phoneShow.add(dcd);
            phoneShow.updateUI();
            dcdMap.put(androidDevice.getSerialNo(), dcd);
            comboBox.notifyGroupChange(comboBox.getSelectedGid());
            num.setText((Integer.parseInt(num.getText())+1)+"");
//            OperateAndroid oa = new OperateAndroid(androidDevice.getDevice());
//            OperateAndroid.injectListener(panelScreen,oa);
        }


        devicesDetector.setConnectedListener(new DevicesDetector.DeviceConnectedListener() {
            public void handler(AndroidDevice androidDevice) {
                if (androidDevice.getSerialNo().startsWith("emulator")) return;
                DeviceControlDecorator dcd = new DeviceControlDecorator(androidDevice);
                phoneShow.add(dcd);
                phoneShow.updateUI();
                dcdMap.put(androidDevice.getSerialNo(), dcd);
                DeviceBean deviceBean = deviceService.registerDevice(androidDevice);
                androidDevice.removeForward(deviceBean.getPort(),3321);
                androidDevice.createForward(deviceBean.getPort(), 3321);
                androidDevice.executeShellCommand("am start -n com.zoke.wechatautomate/com.zoke.wechatautomate.MainActivity", new NullOutputReceiver());
                dbMap.put(deviceBean.getSerialNo(), deviceBean);
                comboBox.notifyGroupChange(comboBox.getSelectedGid());
                num.setText((Integer.parseInt(num.getText())+1)+"");
            }
        });
        devicesDetector.setDisConnectedListener(new DevicesDetector.DeviceDisConnectedListener() {
            public void handler(AndroidDevice androidDevice) {
                androidDevice.stopScreenCaptureThread();
                phoneShow.remove(dcdMap.get(androidDevice.getSerialNo()));
                phoneShow.repaint();
                deviceService.setDeviceOffline(androidDevice.getSerialNo());
                dbMap.remove(androidDevice.getSerialNo());
                comboBox.notifyGroupChange(comboBox.getSelectedGid());
                num.setText((Integer.parseInt(num.getText())-1)+"");
                choosedDevice.remove(androidDevice.getSerialNo());
            }
        });

        new Thread(new Runnable() {
            public void run() {
                InitJob.initJob();
            }
        }).start();

    }

    private List<DeviceBean> getDeviceBeanList() {
        List<DeviceBean> dbs = new ArrayList<DeviceBean>();
        for (Map.Entry<String, DeviceBean> entry : dbMap.entrySet()) {
            dbs.add(entry.getValue());
        }
        return dbs;
    }

    private List<DeviceBean> getChoosedDeviceBeanList() {
        List<DeviceBean> dbs = new ArrayList<DeviceBean>();
        for(String serialNo : choosedDevice){
            dbs.add(dbMap.get(serialNo));
        }
        return dbs;
    }

    private List<AndroidDevice> getChoosedADeviceBeanList() {
        List<AndroidDevice> dbs = new ArrayList<AndroidDevice>();
        for(String serialNo : choosedDevice){
            dbs.add(dcdMap.get(serialNo).getAndroidDevice());
        }
        return dbs;
    }



}